package com.zhongwang.business.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.MultipartConfigElement;
import java.io.File;

/**
 *  应用配置
 *
 * @author China.sgl
 * @date 2019/9/18 08:56
 */
@Configuration
public class ApplicationConfig implements WebMvcConfigurer {

    /** 上传路径 */
    @Value("${user.upload.path}")
    private String filePath;
    /** 临时目录 */
    @Value("${user.upload.temp}")
    private String location;

    /**
     * 默认首页的设置，当输入域名是可以自动跳转到默认指定的网页
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 本地文件上传路径
        registry.addResourceHandler("/files/**").addResourceLocations("file:" + filePath);
    }

    /**
     * 自定义拦截规则
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    }

    /**
     * 文件上传临时路径
     */
    @SuppressWarnings("ResultOfMethodCallIgnored")
    @Bean
    MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        // 设置临时文件路径，以防长时间不操作后删除临时文件导致报错
        File tmpFile = new File(location);
        if (!tmpFile.exists()) {
            tmpFile.mkdirs();
        }
        factory.setLocation(location);
        return factory.createMultipartConfig();
    }

    /**
     * 使用springboot 内置tomcat服务器需做如下配置，使用外部独立服务器不可使用此配置
     *
     * @return ServerEndpointExporter
     */
    /*@Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }*/
}
